<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch, toRaw } from "vue";
import { getDeviceConfigApi, setDeviceConfigApi } from '@/api/configs/deviceConfig';
import { useI18n } from "vue-i18n";
import { IsBelongM1, IsBelongM2 } from "@/utils/appCommon/appCommonOptions/products";
import { DeviceModel } from "@/api/products/device";
import { formatTimestampToDatetime } from "@/utils/appCommon/timeUtil";
import { ElMessageBox, ElMessage } from "element-plus";
import CopyDevices from './CopyDevices.vue';

const emit = defineEmits(['onsubmit']);

const props = defineProps({
  params: {
    type: Object,
    required: true
  },
  deviceNo: {
    type: String,
    required: true
  },
  deviceOptions: {
    type: Array,
    required: false,
    default: [],
  },
  forceRefresh: {
    type: Number,
    required: false,
    default: 0
  }
});

interface AeFirConfig {
  firLow: number;
  firHigh: number;
  firEnable: number;
  updatetime?: number;
}

interface AeParamConfig {
  aeMeasureSpeed: number;
}

const i18n = useI18n();

const current = ref({
  configKey: "fir",
  deviceNo: "",
  productId: 0,
  productKey: "",
  updatedAt: 0,
})

const currentDeviceInfo = ref<DeviceModel>();
const paramConfig = ref<AeParamConfig>({
  aeMeasureSpeed: 0
});
const copyDevices = ref<string[]>([]);

const form = ref<AeFirConfig>({
  firLow: 0,
  firHigh: 0,
  firEnable: 0,
});

watch(
  () => props,
  (newVal) => {
    current.value.updatedAt=0
    current.value.deviceNo = newVal.deviceNo;
    current.value.productId = newVal.params.productId;
    current.value.productKey = newVal.params.productKey;
    setTimeout(async ()=>{
      await loadConfig();
    })
  },{
    deep: true, immediate: true
  }
);

const systemTime = computed(() => {
  if(!current.value.updatedAt || current.value.updatedAt === 0){
    return "-";
  }
  return formatTimestampToDatetime(current.value.updatedAt)
})

const loading = ref(false);

// 加载配置
const loadConfig = async () => {
  try {
    loading.value = true;

    // 加载FIR配置
    const firRes = await getDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
    });
    if (firRes.data?.configValue) {
      form.value = JSON.parse(firRes.data?.configValue);
      form.value.updatetime =  firRes.data?.updatedAt
    }
    // 更新当前时间戳
    if (form.value.updatetime) {
      current.value.updatedAt = form.value.updatetime;
    }
    // 加载参数配置，获取采集速率
    const paramRes = await getDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: "param",
    });
    if (paramRes.data?.configValue) {
      paramConfig.value = paramRes.data.configValue;
    }
  } catch (error) {
    console.error('加载配置失败:', error);
  } finally {
    loading.value = false;
  }
};

// 保存配置
const saveConfig = async () => {
  try {
    loading.value = true;
    await setDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
      configValue: form.value,
      copyDevices: copyDevices.value
    });
    // 重新加载配置以更新时间戳
    setTimeout(async ()=>{
      await loadConfig();
    },2000)

    ElMessage.success(i18n.t('buttons.tips.success'));
  } catch (error) {
    ElMessage.error(i18n.t('buttons.tips.fail'));
  } finally {
    loading.value = false;
  }
};

// 校验方法
const validateForm = (): boolean => {
  if(IsBelongM2(current.value.productKey)){
    // 1. 验证高通滤波器小于低通滤波器
    if (form.value.firHigh > form.value.firLow) {
      ElMessage.error(i18n.t('buttons.tips.highPassLessLowPass'));
      return false;
    }

    // 2. 验证低通不大于采集速率一半
    if (paramConfig.value.aeMeasureSpeed > 0) {
      const maxLowPass = paramConfig.value.aeMeasureSpeed / 2;
      if (form.value.firLow > maxLowPass) {
        ElMessage.error(i18n.t('buttons.tips.lowPassNotGreaterHalfSampleRate'));
        return false;
      }
    } else {
      ElMessage.warning('未获取到采集速率信息，请先配置参数');
      return false;
    }
  }
  return true;
};

// 修改保存配置方法，添加二次确认和校验
const handleSaveConfig = async () => {
  try {
    // 先进行表单校验
    if (!validateForm()) {
      return;
    }

    // 显示确认对话框
    await ElMessageBox.confirm(
      i18n.t('buttons.tips.confirmSaveConfig') + "?",
      "",
      {
        confirmButtonText: i18n.t('buttons.confirm'),
        cancelButtonText: i18n.t('buttons.cancel'),
        type: 'warning'
      }
    );

    // 用户确认后执行保存操作
    await saveConfig();
  } catch (error: any) {
    // 用户取消或其他错误，不做任何操作
    if (error.name !== 'Error') {
      console.log('保存已取消');
    }
  }
};

onMounted(() => {
});
</script>

<template>
  <div class="ae-fir-config">
    <el-form :model="form" >
      <el-form-item :label="i18n.t('device.deviceNo')" prop="deviceNo">
        <el-input v-model="current.deviceNo" disabled />
      </el-form-item>

      <el-form-item :label="i18n.t('device.aefir.FIR_LOW')+ '(kHz)'" prop="firLow">
        <el-input-number v-model="form.firLow" :min="0" style="min-width:200px;" />
        <div v-if="paramConfig.aeMeasureSpeed > 0" class="hint-text">
          {{ i18n.t('device.aefir.MAX_LOW_PASS') }}: {{ paramConfig.aeMeasureSpeed / 2 }}kHz
        </div>
      </el-form-item>

      <el-form-item :label="i18n.t('device.aefir.FIR_HIGH')+ '(kHz)'" prop="firHigh">
        <el-input-number v-model="form.firHigh" :min="0" style="min-width:200px;" />
      </el-form-item>

      <el-form-item :label="i18n.t('device.aefir.FIR_ENABLE')" prop="firEnable">
        <el-radio-group v-model="form.firEnable">
          <el-radio :label="0">{{ i18n.t('buttons.no') }}</el-radio>
          <el-radio :label="1">{{ i18n.t('buttons.yes') }}</el-radio>
        </el-radio-group>
      </el-form-item>


      <!-- 复制设备配置 -->
      <el-form-item :label="i18n.t('device.copyDevices.title')">
        <CopyDevices
          :device-no="current.deviceNo"
          v-model="copyDevices"
        />
      </el-form-item>

      <el-form-item :label="i18n.t('device.aeparam.SYSTEM_TIME')">
        <el-input v-model="systemTime" type="text" disabled></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleSaveConfig" style="min-width: 150px;">
          {{i18n.t('buttons.submit')}}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.ae-fir-config {
  padding: 20px;
  overflow-x: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.hint-text {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}
</style>
